
package com.sugar.note;

import java.io.IOException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.media.AudioManager.OnAudioFocusChangeListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class AlarmAlertService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private long mNoteId;
    private static final String TAG = "AlarmAlertActivity";
    private String mSnippet = "";
    private static final int SNIPPET_PREW_MAX_LEN = 60;
    MediaPlayer mPlayer;
    private Context mCtx;
    private String mAlarmText;
    private static final int EVENT_NOTE_ALARMALERT = 3000;
    private static final int NOTE_ALARMALERT_TIME = 300000;//300000
    private static final int NOTE_ALARMALERT_INTERVAL_TIME = 300000;
    private NoteHomeReceiver mReceiverHome = new NoteHomeReceiver();
    private IntentFilter mIntentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    //private ArrayList<NoteItem> notelist;
    
    //fukang.li date20151024 for MYOSL-464,start
    private boolean mAudioFocus = false;
    AudioManager mAudioManager;
    OnAudioFocusChangeListener afChangeListener;
    //fukang.li date20151024 for MYOSL-464,end
    static final int NOTIFICATION_ID = 0x1123;
    private boolean isAudioStop = false;
    int alert_num;
    Intent startIntent;

    @Override
    public void onCreate() {
        super.onCreate();
        mCtx = this;
        mIntentFilter.addAction(PublicUtils.ACTION_ALERT_CLOSE);
        mIntentFilter.addAction(PublicUtils.ACTION_NOTEALARM_DELETE);
        registerReceiver(mReceiverHome, mIntentFilter);

        
        alert_num = PublicUtils.getAlarmAlertNum(mCtx.getContentResolver(), mNoteId);
        // notelist = intent.getParcelableArrayListExtra("notelist");

        
    }
    
    public Handler mAlarmAlertHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            
            switch (msg.what) {
            case EVENT_NOTE_ALARMALERT:
                    isAudioStop = true;
                    abandonAudioFocus();//
                    stopAlarmSound();
                    break;
                default:
                    break;
            }
        }
    };
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startIntent = intent;
        try {
            Log.e(TAG,"noteId:"+mNoteId);
            mNoteId = Long.valueOf(startIntent.getData().getPathSegments().get(1));
            mSnippet = PublicUtils.getSnippetById(this.getContentResolver(), mNoteId);
            mSnippet = mSnippet.length() > SNIPPET_PREW_MAX_LEN ? mSnippet.substring(0,
                    SNIPPET_PREW_MAX_LEN) + getResources().getString(R.string.notelist_string_info)
                    : mSnippet;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            return 0;
        }

        if (!mSnippet.equals("")) {
            mAlarmText = mSnippet;
        } else {
            mAlarmText = getResources().getString(R.string.default_note_text);
        }
        
        
        //
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        
        afChangeListener = new OnAudioFocusChangeListener() {
            public void onAudioFocusChange(int focusChange) {
                switch (focusChange) {
                    case AudioManager.AUDIOFOCUS_GAIN:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_GAIN");
                        mAudioFocus = true;
                        if(mPlayer == null && !isAudioStop)
                            initMediaPlayer();
                        else if(!mPlayer.isPlaying() && !isAudioStop)
                            mPlayer.start();
                        mPlayer.setVolume(1.0f, 1.0f);
                        break;
                    case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_GAIN_TRANSIENT");
                        mAudioFocus = true;
                        if(mPlayer == null && !isAudioStop)
                            initMediaPlayer();
                        else if(!mPlayer.isPlaying() && !isAudioStop)
                            mPlayer.start();
                        mPlayer.setVolume(1.0f, 1.0f);
                        break;
                    case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK");
                        mAudioFocus = true;
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_LOSS");
                        mAudioFocus = false;
                        stopAlarmSound();
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_LOSS_TRANSIENT");
                        mAudioFocus = false;
                        if(mPlayer != null && mPlayer.isPlaying())
                            mPlayer.pause();
//                        stopAlarmSound();
                        break;
                    case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                        Log.i(TAG, "AudioFocusChange AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
                        mAudioFocus = false;
                        if(mPlayer != null && mPlayer.isPlaying())
                            mPlayer.setVolume(0.1f, 0.1f);
                        //stopAlarmSound();
                        break;
                    default:
                        Log.i(TAG, "AudioFocusChange focus = " + focusChange);
                        break;
                }
            }
        };
        
        if (PublicUtils.visibleInNoteDatabase(getContentResolver(), mNoteId)) {
//            showActionDialog();
            showNotice();
            requestAudioFocus();
            if(mAudioFocus)
                initMediaPlayer();
            Log.i(TAG, "over onCreate");
        } else {
            Log.e(TAG,"not exist");
//            finish();
        }
        
        

        
        mAlarmAlertHandler.sendEmptyMessageDelayed(EVENT_NOTE_ALARMALERT, NOTE_ALARMALERT_TIME);
        
        return START_STICKY;
    }

    public void showNotice(){
        Intent mIntent = new Intent(this,this.getClass());
        mIntent.setData(startIntent.getData());
        PendingIntent pi = PendingIntent.getActivity(this, (int)mNoteId, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        Intent enterIntent = new Intent(this, NoteView.class);
        Uri noteUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, mNoteId);
        enterIntent.setData(noteUri);
        enterIntent.putExtra("AlarmStartNoteView", true);
        PendingIntent enterPendingIntent = PendingIntent.getActivity(this, 0, enterIntent, 0);
        //START
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.drawable.stat_notify_alarm)
        .setTicker(mAlarmText)
        .setWhen(0)
        .setContentTitle(getResources().getString(R.string.note_alarm_title))
        .setContentText(mAlarmText)
        .setContentIntent(enterPendingIntent)
        .setAutoCancel(false)
        .setDefaults(Notification.DEFAULT_LIGHTS)
        //.setDeleteIntent(createClearMissedCallsIntent())
        .setPriority(Notification.PRIORITY_HIGH)
        .setNumber(alert_num)
        .setFullScreenIntent(enterPendingIntent, true)
        .setOngoing(true);
        
//        Notification notification = builder.getNotification();
        // notification.flags = Notification.FLAG_NO_CLEAR;
        // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        builder.addAction(android.R.drawable.stat_notify_chat,
                getString(R.string.notealert_enter),
                enterPendingIntent);

        Intent closeIntent = new Intent(PublicUtils.ACTION_ALERT_CLOSE);
        closeIntent.putExtra("URI", noteUri);
        PendingIntent closePendingIntent = PendingIntent.getBroadcast(mCtx, (int) mNoteId, closeIntent, 0);
        builder.addAction(android.R.drawable.ic_notification_clear_all,
                getString(R.string.notealert_ok),
                closePendingIntent);

        // END

//        Notification notify = new Notification();
//        notify.icon = R.drawable.app_notes;
//        if (!mSnippet.equals("")) {
//            notify.tickerText = mSnippet;
//        } else {
//            notify.tickerText = getResources().getString(R.string.default_note_text);
//        }
//        notify.when = System.currentTimeMillis();
//        notify.defaults = Notification.DEFAULT_LIGHTS;
//        notify.flags = Notification.FLAG_NO_CLEAR;
//        notify.setLatestEventInfo(mCtx, getResources().getString(R.string.note_alarm_title), notify.tickerText, pi);
        
        
        NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        //send
        notificationManager.notify((int) (NOTIFICATION_ID + mNoteId), builder.build());
    }
    
    public void closeNotice(){
        NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        notificationManager.cancel((int) (NOTIFICATION_ID + mNoteId));
    }
    
    public void closeNoteAlarmDialog() {
    
        Log.e("nb alarm", "AlarmAlertActivity andy3344  closeNoteAlarmDialog");
        Intent intent = new Intent(PublicUtils.ACTION_NOTEALARM_ALERT);
        sendBroadcast(intent);
        abandonAudioFocus();//
        stopAlarmSound();
        closeNotice();
//        finish();
    }

    private boolean isScreenOn() {
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }

    private void playAlarmSound() {
        Log.i("AlarmAlert","playAlarmSound AA");
        
        // fukang.li date20151014 for MYOSL-464
        // sendMusicAction(CMDPAUSE);
        
        
        Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);

        int silentModeStreams = Settings.System.getInt(getContentResolver(),
                Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);

        Log.i("AlarmAlert","url:"+url.toString());
        Log.i("AlarmAlert","silentModeStreams:"+ silentModeStreams);
        
        if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
            mPlayer.setAudioStreamType(silentModeStreams);
        } else {
            mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        }
        try {
            mPlayer.reset();mPlayer.setDataSource(this, url);
            mPlayer.setLooping(true);
            mPlayer.prepare();
            mPlayer.start();
            Log.i("AlarmAlert","playAlarmSound mPlayer.start()");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopAlarmSound() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.reset();//
            mPlayer.release();
            mPlayer = null;
            //sendMusicAction(CMDPLAY);
        }
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(mReceiverHome);
        abandonAudioFocus();
        stopAlarmSound();//
        closeNotice();
        super.onDestroy();
    }
    
    private class NoteHomeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra("reason");
                if (reason != null && reason.equals("homekey")) {
                    stopAlarmSound();
                }
            } else if (action.equals(PublicUtils.ACTION_ALERT_CLOSE)) {// fukang.li date20151023
                Uri noteUri = ContentUris
                        .withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, mNoteId);
                Uri muri = (Uri) intent.getExtras().get("URI");
                if (noteUri != null && noteUri.equals(muri)) {
                    closeNoteAlarmDialog();
                }
            }
            if (action.equals(PublicUtils.ACTION_NOTEALARM_DELETE)) {
                Uri noteUri = ContentUris
                        .withAppendedId(NotePad.Notes.CONTENT_ID_URI_BASE, mNoteId);
                Uri muri = (Uri) intent.getExtras().get("URI");
                if (noteUri != null && noteUri.equals(muri)) {
                    abandonAudioFocus();
                    stopAlarmSound();
                }
            }

        }
    }
    
    /**
     * fukang.li
     * date20151024 for MYOSL-464
     */
    private void requestAudioFocus() {
        Log.v(TAG, "requestAudioFocus mAudioFocus = " + mAudioFocus);
        if (!mAudioFocus) {
            int result = mAudioManager.requestAudioFocus(afChangeListener,
                    AudioManager.STREAM_MUSIC, // Use the music stream.
                    AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
            if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                mAudioFocus = true;
            } else {
                Log.e(TAG, "AudioManager request Audio Focus result = " + result);
            }
        }
    }

    private void abandonAudioFocus() {
        Log.v(TAG, "abandonAudioFocus mAudioFocus = " + mAudioFocus);
        if (mAudioFocus) {
            mAudioManager.abandonAudioFocus(afChangeListener);
            mAudioFocus = false;
        }
    }
    
    private void initMediaPlayer(){
        if(isAudioStop)
            return;
        Log.i("AlarmAlert","before new ");
        mPlayer = new MediaPlayer();
        Uri url = RingtoneManager.getActualDefaultRingtoneUri(this, RingtoneManager.TYPE_ALARM);
//        mPlayer = MediaPlayer.create(this, url);
        Log.i("AlarmAlert","after new before play");
        

        int silentModeStreams = Settings.System.getInt(getContentResolver(),
                Settings.System.MODE_RINGER_STREAMS_AFFECTED, 0);

        Log.i("AlarmAlert","url:"+url.toString());
        Log.i("AlarmAlert","silentModeStreams:"+ silentModeStreams);
        
        if ((silentModeStreams & (1 << AudioManager.STREAM_ALARM)) != 0) {
            mPlayer.setAudioStreamType(silentModeStreams);
        } else {
            mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
        }
        try {
            //mPlayer.reset();
            mPlayer.setDataSource(this, url);
            mPlayer.setLooping(true);
            mPlayer.prepare();
//            mPlayer.
            mPlayer.start();
            Log.i("AlarmAlert","playAlarmSound mPlayer.start()");
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}
